package com.zhkj.txg.module.product.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.txg.R
import com.zhkj.txg.module.product.adapter.SharePictureAdapter
import com.zhkj.txg.module.product.popup.SharePopupWindow
import com.zhkj.txg.module.product.vm.ShareViewModel
import com.zhkj.txg.utils.ClipBoardUtils
import com.zhkj.txg.utils.ShareUtils
import kotlinx.android.synthetic.main.activity_share_friend.*

class ShareFriendActivity : ViewModelActivity<ShareViewModel>() {

    companion object {
        private val TYPE_TEXT = "text"
        private val TYPE_IMAGE = "image"
        fun open(activity: Activity, text: String, images: Array<String>) {
            val intent = Intent(activity, ShareFriendActivity::class.java)
                .putExtra(TYPE_TEXT, text).putExtra(TYPE_IMAGE, images)
            activity.startActivity(intent)
        }
    }

    private val pictureAdapter = SharePictureAdapter()
    private val sharePopupWindow: SharePopupWindow by lazy {
        SharePopupWindow(this) {
//            ShareUtils.share2Circle(
//                this, intent.getStringExtra(TYPE_TEXT) ?: "",
//                if (it.isNullOrEmpty()) "" else it[0].path
//            )
            ShareUtils.jump2WeChat(this)
            sharePopupWindow.dismiss()
        }
    }

    override fun statusTitleBar(): View? = titleShare
    override val layoutResId: Int = R.layout.activity_share_friend
    override fun setViewModel(): ShareViewModel = createViewModel()

    override fun initUI() {
        val images = intent.getStringArrayExtra(TYPE_IMAGE)
        val text = intent.getStringExtra(TYPE_TEXT)

        if (text?.isNotEmpty() == true) {
            viewShareContent.visibility = View.VISIBLE
            tvShareContent.text = text
        }
        if (images?.isNotEmpty() == true) {
            viewSharePicture.visibility = View.VISIBLE
            rvShare.layoutManager = GridLayoutManager(this, 3)
            rvShare.adapter = pictureAdapter
            pictureAdapter.addData(images.asList())
        }
        // 一键发圈
        tvShareOneKey.setOnClickListener {
            // 复制文字
            ClipBoardUtils.copy(this, text ?: "")
            // 下载图片
            images?.let {
                requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, {
                    viewModel.savePicture(this, it.asList())
                }, { toast(getString(R.string.read_permission_deny)) })
            }
        }
    }

    override fun initViewModel() {
        // 保存图片数据观察者
        viewModel.savePictureLiveData.observe(this, Observer {
            sharePopupWindow.setData(it)
            sharePopupWindow.showPopupWindow()
        })
    }
}